package com.example.managemyself.util;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.example.managemyself.config.AppConfig;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * DeepSeek API帮助类
 * 用于AI对话和解卦功能
 */
public class DeepSeekHelper {
    
    private static final String TAG = "DeepSeekHelper";
    
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build();
    
    private static final ExecutorService executor = Executors.newCachedThreadPool();
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());
    
    private static Context applicationContext;
    
    /**
     * 初始化DeepSeekHelper
     */
    public static void initialize(Context context) {
        applicationContext = context.getApplicationContext();
    }
    
    /**
     * 回调接口
     */
    public interface DeepSeekCallback {
        void onResponse(String response);
        void onError(String error);
    }
    
    /**
     * 获取AI解释/对话
     * @param userMessage 用户消息
     * @param callback 回调接口
     */
    public static void getChatResponse(String userMessage, DeepSeekCallback callback) {
        executor.execute(() -> {
            try {
                // 首先尝试从数据库获取API密钥
                String apiKey = null;
                if (applicationContext != null) {
                    ApiKeyManager apiKeyManager = ApiKeyManager.getInstance(applicationContext);
                    apiKey = apiKeyManager.getDeepSeekApiKeySync();
                }
                
                // 如果数据库中没有，则使用配置文件中的默认密钥
                if (apiKey == null || apiKey.isEmpty()) {
                    AppConfig config = AppConfig.getInstance();
                    apiKey = config.getDeepSeekApiKey();
                }
                
                if (apiKey == null || apiKey.isEmpty() || apiKey.equals("your_deepseek_api_key")) {
                    mainHandler.post(() -> callback.onError("DeepSeek API密钥未配置，请在设置中添加API密钥"));
                    return;
                }
                
                AppConfig config = AppConfig.getInstance();
                String apiUrl = config.getDeepSeekApiUrl();
                String model = config.getDeepSeekModel();
                
                // 构建请求JSON
                JSONObject requestJson = new JSONObject();
                requestJson.put("model", model);
                requestJson.put("max_tokens", 2000);
                requestJson.put("temperature", 0.7);
                
                JSONArray messages = new JSONArray();
                JSONObject systemMessage = new JSONObject();
                systemMessage.put("role", "system");
                systemMessage.put("content", "你是一个智能助手，请用中文回答用户的问题。回答要简洁明了，有用且准确。");
                messages.put(systemMessage);
                
                JSONObject userMessageObj = new JSONObject();
                userMessageObj.put("role", "user");
                userMessageObj.put("content", userMessage);
                messages.put(userMessageObj);
                
                requestJson.put("messages", messages);
                
                RequestBody requestBody = RequestBody.create(
                    requestJson.toString(),
                    MediaType.parse("application/json")
                );
                
                Request request = new Request.Builder()
                        .url(apiUrl)
                        .addHeader("Authorization", "Bearer " + apiKey)
                        .addHeader("Content-Type", "application/json")
                        .post(requestBody)
                        .build();
                
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e(TAG, "DeepSeek API请求失败", e);
                        mainHandler.post(() -> callback.onError("网络请求失败: " + e.getMessage()));
                    }
                    
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        try {
                            if (!response.isSuccessful()) {
                                String errorMsg = "API请求失败，状态码: " + response.code();
                                if (response.body() != null) {
                                    String errorBody = response.body().string();
                                    Log.e(TAG, "DeepSeek API错误响应: " + errorBody);
                                    errorMsg += "\n错误详情: " + errorBody;
                                }
                                final String finalErrorMsg = errorMsg;
                                mainHandler.post(() -> callback.onError(finalErrorMsg));
                                return;
                            }
                            
                            String responseBody = response.body().string();
                            Log.d(TAG, "DeepSeek API响应: " + responseBody);
                            
                            JSONObject jsonResponse = new JSONObject(responseBody);
                            
                            if (jsonResponse.has("error")) {
                                JSONObject error = jsonResponse.getJSONObject("error");
                                String errorMessage = error.optString("message", "未知错误");
                                mainHandler.post(() -> callback.onError("API错误: " + errorMessage));
                                return;
                            }
                            
                            // 解析响应
                            JSONArray choices = jsonResponse.getJSONArray("choices");
                            if (choices.length() > 0) {
                                JSONObject choice = choices.getJSONObject(0);
                                JSONObject message = choice.getJSONObject("message");
                                String content = message.getString("content");
                                
                                mainHandler.post(() -> callback.onResponse(content));
                            } else {
                                mainHandler.post(() -> callback.onError("API响应格式错误：没有找到回答"));
                            }
                            
                        } catch (JSONException e) {
                            Log.e(TAG, "解析DeepSeek响应失败", e);
                            mainHandler.post(() -> callback.onError("解析响应失败: " + e.getMessage()));
                        }
                    }
                });
                
            } catch (JSONException e) {
                Log.e(TAG, "构建DeepSeek请求失败", e);
                mainHandler.post(() -> callback.onError("构建请求失败: " + e.getMessage()));
            }
        });
    }
    
    /**
     * 获取解卦建议
     * @param hexagramName 卦名
     * @param question 问题
     * @param callback 回调接口
     */
    public static void getDivinationAdvice(String hexagramName, String question, DeepSeekCallback callback) {
        String prompt = String.format(
            "请为以下易经卦象提供解释和建议：\n" +
            "卦象：%s\n" +
            "问题：%s\n\n" +
            "请从以下几个方面进行分析：\n" +
            "1. 卦象的基本含义\n" +
            "2. 对当前问题的指导意义\n" +
            "3. 具体的行动建议\n" +
            "4. 需要注意的事项\n\n" +
            "回答要简洁明了，富有智慧。",
            hexagramName, question
        );
        
        getChatResponse(prompt, callback);
    }
    
    /**
     * 获取任务建议
     * @param taskTitle 任务标题
     * @param taskDescription 任务描述
     * @param callback 回调接口
     */
    public static void getTaskAdvice(String taskTitle, String taskDescription, DeepSeekCallback callback) {
        String prompt = String.format(
            "请为以下任务提供完成建议：\n" +
            "任务标题：%s\n" +
            "任务描述：%s\n\n" +
            "请提供：\n" +
            "1. 任务分解建议\n" +
            "2. 执行步骤\n" +
            "3. 注意事项\n" +
            "4. 时间安排建议\n\n" +
            "回答要实用且易于执行。",
            taskTitle, taskDescription
        );
        
        getChatResponse(prompt, callback);
    }
    
    /**
     * 获取健康建议
     * @param healthData 健康数据描述
     * @param callback 回调接口
     */
    public static void getHealthAdvice(String healthData, DeepSeekCallback callback) {
        String prompt = String.format(
            "基于以下健康数据，请提供健康建议：\n" +
            "%s\n\n" +
            "请提供：\n" +
            "1. 数据分析\n" +
            "2. 健康状况评估\n" +
            "3. 改善建议\n" +
            "4. 注意事项\n\n" +
            "注意：这只是参考建议，如有健康问题请咨询专业医生。",
            healthData
        );
        
        getChatResponse(prompt, callback);
    }
    
    /**
     * 获取解释/解读（兼容旧版本方法名）
     * @param prompt 提示信息
     * @param callback 回调接口
     */
    public static void getInterpretation(String prompt, DeepSeekCallback callback) {
        getChatResponse(prompt, callback);
    }
} 